package org.anupta.game.server.game.packet.account.character.delete;

import org.anupta.game.entity.dao.DAO;
import org.anupta.game.entity.entities.Account;
import org.anupta.game.entity.entities.Player;
import org.anupta.game.main.Main;
import org.anupta.game.server.game.client.GameClient;
import org.anupta.game.server.game.packet.GamePacket;
import org.anupta.game.server.game.packet.account.AccountList;
import org.anupta.game.server.game.packet.account.character.delete.answer.CharacterDeleteError;

public class CharacterDelete extends GamePacket {
	private int charId = 0;
	private String answer = null;
	
	public CharacterDelete(GameClient client, String message) {
		super(client, message);
		unpack();
		doPacket();
	}

	@Override
	public void unpack() {
		String[] infos = packetIn.substring(2).split("\\|");
		charId = Integer.parseInt(infos[0]);
		if(infos.length == 2){
			answer = infos[1];
		}
	}

	@Override
	public void pack() {
	}

	@Override
	public void doPacket() {
		Player player = DAO.getDao(Player.class).find(charId);
		if(player != null){
			if(answer != null){
				if(answer.equals(client.getAccount().getAnswer())){
					DAO.getDao(Player.class).delete(player);
					client.getAccount().delPlayer(player);
					DAO.getDao(Account.class).update(client.getAccount());
					new AccountList(client);
					Main.out.println(new StringBuilder("Player deleted for : ").append(client.getIp()).toString());
					return;
				}else{
					new CharacterDeleteError(client);
					return;
				}
			}
			DAO.getDao(Player.class).delete(player);
			client.getAccount().delPlayer(player);
			DAO.getDao(Account.class).update(client.getAccount());
			new AccountList(client);
			Main.out.println(new StringBuilder("Player deleted for : ").append(client.getIp()).toString());
		}else{
			new CharacterDeleteError(client);
		}
	}
}
